package api

import (
	"aglaia/global"
	"aglaia/internal/service"
	"aglaia/pkg/app"
	"aglaia/pkg/errcode"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Auth(c *gin.Context) {
	param := service.AuthRequest{}
	response := app.NewResponse(c)
	if err := response.Bind(&param); err != nil {
		global.Logger.Errorf("response.Bind error: %v\n", err)
		response.ToErrorResponse(errcode.InvalidParams)
		return
	}

	svc := service.New(c.Request.Context())
	auth, surplus, err := svc.CheckAuth(&param, c.Request.RemoteAddr)
	if err != nil {
		global.Logger.Errorf("svc.CheckAuth err: %v\n", err)
		response.ToErrorResponse(errcode.UnauthorizedAuthNotExist.WithDetails(strconv.Itoa(surplus)))
		return
	}

	token, err := app.GenerateToken(auth.Id, param.AppKey, param.AppSecret)
	if err != nil {
		global.Logger.Errorf("app.GenerateToken err: %v\n", err)
		response.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
		return
	}

	response.ToResponse(gin.H{
		"token": token,
	})
}
